<template>
  <div class="drawing-canvas-container">
    <canvas
      ref="canvasRef"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="stopDrawing"
      @mouseleave="stopDrawing"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="stopDrawing"
    ></canvas>
    <div class="toolbar">
      <div class="tools-group">
        <el-button-group>
          <el-button :type="tool === 'pen' ? 'primary' : ''" @click="setTool('pen')">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button :type="tool === 'eraser' ? 'primary' : ''" @click="setTool('eraser')">
            <el-icon><Delete /></el-icon>
          </el-button>
        </el-button-group>
      </div>
      <div class="pen-settings">
        <el-color-picker v-model="penColor" size="small" class="color-picker" />
        <el-slider v-model="penSize" :min="1" :max="20" :step="1" class="pen-size-slider" />
      </div>
      <div class="action-buttons">
        <el-button-group>
          <el-button @click="clearCanvas" type="danger" circle>
            <el-icon><Delete /></el-icon>
          </el-button>
          <el-button @click="undo" :disabled="!canUndo" circle>
            <el-icon><Back /></el-icon>
          </el-button>
          <el-button @click="redo" :disabled="!canRedo" circle>
            <el-icon><Right /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Edit, Delete, Back, Right } from '@element-plus/icons-vue'

const canvasRef = ref<HTMLCanvasElement | null>(null)
const ctx = ref<CanvasRenderingContext2D | null>(null)
const isDrawing = ref(false)
const tool = ref('pen')
const penColor = ref('#000000')
const penSize = ref(2)
const history = ref<ImageData[]>([])
const historyStep = ref(-1)

// 处理触摸事件开始
const handleTouchStart = (event: TouchEvent) => {
  event.preventDefault()
  const touch = event.touches[0]
  const canvas = canvasRef.value
  if (!canvas) return

  const rect = canvas.getBoundingClientRect()
  const x = touch.clientX - rect.left
  const y = touch.clientY - rect.top
  
  isDrawing.value = true
  ctx.value?.beginPath()
  ctx.value?.moveTo(x, y)
}

// 处理触摸移动事件
const handleTouchMove = (event: TouchEvent) => {
  event.preventDefault()
  if (!isDrawing.value) return

  const touch = event.touches[0]
  const canvas = canvasRef.value
  if (!canvas) return

  const rect = canvas.getBoundingClientRect()
  const x = touch.clientX - rect.left
  const y = touch.clientY - rect.top

  if (ctx.value) {
    ctx.value.lineWidth = tool.value === 'eraser' ? penSize.value * 2 : penSize.value
    ctx.value.strokeStyle = tool.value === 'eraser' ? '#ffffff' : penColor.value
    ctx.value.lineTo(x, y)
    ctx.value.stroke()
  }
}

const canUndo = ref(false)
const canRedo = ref(false)

// 初始化画布
onMounted(() => {
  const canvas = canvasRef.value!
  const container = canvas.parentElement!
  const containerWidth = container.clientWidth
  
  // 设置画布尺寸，移动端下限制最大宽度
  const maxWidth = Math.min(containerWidth, 600)
  const aspectRatio = 3/4
  
  canvas.width = maxWidth
  canvas.height = maxWidth * aspectRatio
  
  ctx.value = canvas.getContext('2d')!
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
  saveState()
})

// 开始绘画
const startDrawing = (e: MouseEvent) => {
  isDrawing.value = true
  const { offsetX, offsetY } = e
  ctx.value!.beginPath()
  ctx.value!.moveTo(offsetX, offsetY)
}

// 绘画中
const draw = (e: MouseEvent) => {
  if (!isDrawing.value) return
  const { offsetX, offsetY } = e
  
  ctx.value!.strokeStyle = tool.value === 'eraser' ? '#ffffff' : penColor.value
  ctx.value!.lineWidth = tool.value === 'eraser' ? penSize.value * 2 : penSize.value
  
  ctx.value!.lineTo(offsetX, offsetY)
  ctx.value!.stroke()
}

// 停止绘画
const stopDrawing = () => {
  if (isDrawing.value) {
    isDrawing.value = false
    saveState()
  }
}

// 设置工具
const setTool = (newTool: string) => {
  tool.value = newTool
}

// 清空画布
const clearCanvas = () => {
  ctx.value!.clearRect(0, 0, canvasRef.value!.width, canvasRef.value!.height)
  saveState()
}

// 保存状态
const saveState = () => {
  const imageData = ctx.value!.getImageData(0, 0, canvasRef.value!.width, canvasRef.value!.height)
  historyStep.value++
  history.value = history.value.slice(0, historyStep.value)
  history.value.push(imageData)
  updateUndoRedoState()
}

// 撤销
const undo = () => {
  if (historyStep.value > 0) {
    historyStep.value--
    ctx.value!.putImageData(history.value[historyStep.value], 0, 0)
    updateUndoRedoState()
  }
}

// 重做
const redo = () => {
  if (historyStep.value < history.value.length - 1) {
    historyStep.value++
    ctx.value!.putImageData(history.value[historyStep.value], 0, 0)
    updateUndoRedoState()
  }
}

// 更新撤销/重做状态
const updateUndoRedoState = () => {
  canUndo.value = historyStep.value > 0
  canRedo.value = historyStep.value < history.value.length - 1
}

// 将画布内容转换为base64格式
const toDataURL = (type: string = 'image/png'): string => {
  return canvasRef.value!.toDataURL(type)
}

defineExpose({
  toDataURL
})
</script>

<style scoped>
.drawing-canvas-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 20px;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

canvas {
  border: 1px solid #ddd;
  background: white;
  cursor: crosshair;
  width: 100%;
  max-width: 600px;
  height: auto;
  touch-action: none;
}

.toolbar {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tools-group,
.pen-settings,
.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pen-settings {
  flex: 1;
  min-width: 200px;
  display: flex;
  gap: 16px;
  align-items: center;
}

.pen-size-slider {
  flex: 1;
  min-width: 120px;
}

@media screen and (max-width: 768px) {
  .drawing-canvas-container {
    gap: 12px;
    padding: 12px;
  }

  .toolbar {
    padding: 12px;
    gap: 12px;
  }

  .tools-group,
  .pen-settings,
  .action-buttons {
    width: 100%;
    justify-content: center;
  }

  .pen-settings {
    flex-direction: row;
    flex-wrap: nowrap;
  }

  .pen-size-slider {
    min-width: 0;
  }

  .color-picker {
    flex-shrink: 0;
  }
}
</style>